import {def} from "./utils";
import Dep from './Dep';

const arrayPrototype = Array.prototype;

export const arrayMethods = Object.create(Array.prototype);

const methodsNeedChange = [
    'push',
    'pop',
    'shift',
    'unshift',
    'sort',
    'splice',
    'reverse'
];

methodsNeedChange.forEach(method => {
    const original = arrayPrototype[method];

    def(arrayMethods, method, function (...args) {
        console.log(`调用了已修改的数组方法${method}`);
        const result = original.apply(this, args);
        const ob = this.__ob__;
        let inserted = [];

        switch (method) {
            case 'push':
            case 'unshift':
                inserted = args;
                break;
            case 'splice':
                inserted = args.slice(2);
                break;
        }
        if (inserted.length > 0) {
            ob.observeArray(inserted);
        }

        ob.dep.notify();

        return result;
    }, false);
});